package io.gitee.caoxiaoyu97.log.sensitive.logback;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import io.gitee.caoxiaoyu97.log.sensitive.pattern.SensitiveDataConverter;

import java.lang.reflect.Field;

public class LogBackSensitiveDataConverter extends MessageConverter {


    @Override
    public void start() {
        SensitiveDataConverter.init(getOptionList());
        super.start();
    }


    @Override
    public String convert(ILoggingEvent event) {
        String message = event.getFormattedMessage();
        message = SensitiveDataConverter.getInstance().convert(message);
        setFormattedMesage(event,message);
        doErrHandle(event);
        return message;
    }

    private void doErrHandle(ILoggingEvent event) {
        IThrowableProxy throwableProxy = event.getThrowableProxy();
        String message = throwableProxy.getMessage();
        message = SensitiveDataConverter.getInstance().convert(message);
        setMesage(throwableProxy,message);
    }

    private void setMesage(IThrowableProxy event, String message){
        try {
            Class<?> logEventClass = event.getClass();
            Field formattedMessageField = logEventClass.getDeclaredField("message");
            formattedMessageField.setAccessible(true);
            formattedMessageField.set(event, message);
        } catch (Exception e) {
        }
    }

    private void setFormattedMesage(ILoggingEvent event, String message){
        try {
            Class<?> logEventClass = event.getClass();
            Field formattedMessageField = logEventClass.getDeclaredField("formattedMessage");
            formattedMessageField.setAccessible(true);
            formattedMessageField.set(event, message);
        } catch (Exception e) {
        }
    }


}

